#include "CreatePage.h"

CreatePage::CreatePage(QWidget *parent) : QWidget{parent}
{
    setupUI();

    this->setStyleSheet(R"(
        QWidget {
            background-color: #ffffff;
            font-family: "微软雅黑", sans-serif;
        }
        QLineEdit, QTextEdit, QPushButton{
            border: 1px solid #cccccc;
            border-radius: 4px;
        }
        QPushButton:hover {
            background-color: #e6f7ff;
        }
        QToolBar {
            background-color: #f8f8f8;
            border-bottom: 1px solid #dddddd;
        }
    )");
}

void CreatePage::setupUI()
{
    QVBoxLayout *layout = new QVBoxLayout(this);

    // 创建可编辑的标题栏
    titleEdit = new QLineEdit(this);
    titleEdit->setPlaceholderText("请输入文章标题");
    titleEdit->setFont(QFont(titleEdit->font().family(), 16, QFont::Bold));
    layout->addWidget(titleEdit);

    titleEdit->setStyleSheet(R"(
        QLineEdit {
            font-size: 24px;
            font-weight: bold;
            border: 2px solid #aeeaff;
            border-radius: 6px;
            background-color: #f0faff;
        }
    )");

    // 创建工具栏
    toolBar = new QToolBar(this);
    setupToolbar();
    layout->addWidget(toolBar);

    // 创建编辑器
    editor = new BlogTextEdit(this);
    editor->setAcceptRichText(true);
    editor->setPlaceholderText("开始撰写你的文章...");
    layout->addWidget(editor);

    editor->setFrameShape(QFrame::Box);
    editor->setLineWidth(1);
    editor->setStyleSheet(R"(
        QTextEdit {
            border: 1px solid #bbbbbb;
            border-radius: 6px;
        }
    )");

    // 底部布局
    QHBoxLayout *buttonLayout = new QHBoxLayout();

    // 创建上传附件按钮
    uploadButton = new QPushButton("上传附件", this);
    connect(uploadButton, &QPushButton::clicked, [=]()
            {
        QString filePath = QFileDialog::getOpenFileName(this, "选择附件", "", "All Files (*.*)");
        if (!filePath.isEmpty()) {
            attachmentPath = filePath;
            QMessageBox::information(this, "提示", "附件上传成功！");
        } });
    buttonLayout->addWidget(uploadButton, 1);

    // 创建附件售价输入框
    attachmentPriceEdit = new QLineEdit(this);
    attachmentPriceEdit->setPlaceholderText("附件售价（0~1000000）");
    attachmentPriceEdit->setValidator(new QIntValidator(0, 1000000, this));
    attachmentPriceEdit->setText("0");
    attachmentPriceEdit->setStyleSheet(R"(
        QLineEdit, QTextEdit, QPushButton{
            padding: 8px;
        }
    )");
    buttonLayout->addWidget(attachmentPriceEdit, 1);

    QPushButton *previewButton = new QPushButton("预览", this);
    buttonLayout->addWidget(previewButton, 1);

    connect(previewButton, &QPushButton::clicked, [this]()
            {
        QString title = titleEdit->text();
        QString htmlContent = editor->toHtml();
        emit previewSignal(title, htmlContent); });

    // 创建发布文章按钮
    publishButton = new QPushButton("发布文章", this);
    connect(publishButton, &QPushButton::clicked, [=]()
            {
                QString title = titleEdit->text();
                QString htmlContent = editor->toHtml();
                QString price = attachmentPriceEdit->text();
                if (title.isEmpty() || htmlContent.simplified().isEmpty())
                {
                    QMessageBox::warning(this, "提示", "标题或文章内容不能为空！");
                    return;
                }

                QString summary = this->getSummary();

                // 打开预览窗口
                PreviewDialog dialog(title, summary, this);
                if (dialog.exec() == QDialog::Accepted) {
                    QImage coverImage = dialog.getCoverImage(); // 获取封面图片
                    QString tagValue = dialog.getSelectedTag(); // 获取文章标签
                    // TODO: 实现发布逻辑，包括上传封面和文章内容
                    qDebug() << "标题：" << title;
                    qDebug() << "内容：" << htmlContent;
                    qDebug() << "文章标签：" << tagValue;
                    qDebug() << "附件路径：" << attachmentPath;
                    qDebug() << "附件售价：" << price;
                    QFile file("BlogContent.txt"); // 指定输出文件路径
                    // if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
                    //     QTextStream out(&file);
                    //     out << htmlContent; // 将内容写入文件
                    //     file.close();
                    //     qDebug() << "保存成功";
                    // }
                    if (!coverImage.isNull()) {
                        // 上传封面图片
                        QByteArray coverData;
                        QBuffer buffer(&coverData);
                        buffer.open(QIODevice::WriteOnly);
                        coverImage.save(&buffer, "JPG");
                        qDebug() << "封面图片数据大小：" << coverData.size();
                    }
                    else
                    {
                        qDebug() << "封面图片为空";
                    }
                    QMessageBox::information(this, "提示", "文章已发布！");
                } });
    buttonLayout->addWidget(publishButton, 1);

    layout->addLayout(buttonLayout);

    uploadButton->setStyleSheet(R"(
        QPushButton {
            background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #4da6ff, stop:1 #0078ff);
            color: white;
            font-weight: bold;
            border-radius: 6px;
            padding: 8px;
        }
        QPushButton:hover {
            background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #6bbfff, stop:1 #0095ff);
        }
    )");

    previewButton->setStyleSheet(R"(
        QPushButton {
            background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #5cd6d6, stop:1 #00b386);
            color: white;
            font-weight: bold;
            border-radius: 6px;
            padding: 8px;
        }
        QPushButton:hover {
            background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #7de5e5, stop:1 #00cc99);
        }
    )");

    publishButton->setStyleSheet(R"(
        QPushButton {
            background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #ff9999, stop:1 #ff6666);
            color: white;
            font-weight: bold;
            border-radius: 6px;
            padding: 8px;
        }
        QPushButton:hover {
            background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #ffcccc, stop:1 #ff9999);
        }
    )");
}

void CreatePage::setupToolbar()
{
    QAction *boldAct = toolBar->addAction(QIcon(":/editIcon/resoures/editIcon/boldAct.png"), "加粗");
    boldAct->setCheckable(true);
    connect(boldAct, &QAction::toggled, [=](bool checked)
            { editor->setFontWeight(checked ? QFont::Bold : QFont::Normal); });

    QAction *italicAct = toolBar->addAction(QIcon(":/editIcon/resoures/editIcon/italicAct.png"), "斜体");
    italicAct->setCheckable(true);
    connect(italicAct, &QAction::toggled, [=](bool checked)
            { editor->setFontItalic(checked); });

    QAction *underlineAct = toolBar->addAction(QIcon(":/editIcon/resoures/editIcon/underlineAct.png"), "下划线");
    underlineAct->setCheckable(true);
    connect(underlineAct, &QAction::toggled, [=](bool checked)
            { editor->setFontUnderline(checked); });

    toolBar->addSeparator();

    QAction *colorAct = toolBar->addAction(QIcon(":/editIcon/resoures/editIcon/colorAct.png"), "字体颜色");
    connect(colorAct, &QAction::triggered, [=]()
            {
        QColor color = QColorDialog::getColor(Qt::black, this);
        if (color.isValid()) {
            editor->setTextColor(color);
        } });

    // 字号选择
    QSpinBox *fontSizeBox = new QSpinBox();
    fontSizeBox->setRange(8, 72);
    fontSizeBox->setValue(12);      // 默认字号
    fontSizeBox->setFixedWidth(80); // 固定宽度
    connect(fontSizeBox, QOverload<int>::of(&QSpinBox::valueChanged), [=](int size)
            { editor->setFontPointSize(size); });
    toolBar->addWidget(fontSizeBox);

    // 字体选择
    QFontComboBox *fontComboBox = new QFontComboBox();
    connect(fontComboBox, &QFontComboBox::currentFontChanged, [=](const QFont &font)
            { editor->setCurrentFont(font); });
    toolBar->addWidget(fontComboBox);

    toolBar->addSeparator();

    QAction *alignLeftAct = toolBar->addAction(QIcon(":/editIcon/resoures/editIcon/alignLeftAct.png"), "左对齐");
    alignLeftAct->setCheckable(true);
    connect(alignLeftAct, &QAction::triggered, [=]()
            { editor->setAlignment(Qt::AlignLeft); });

    QAction *alignCenterAct = toolBar->addAction(QIcon(":/editIcon/resoures/editIcon/alignCenterAct.png"), "居中对齐");
    alignCenterAct->setCheckable(true);
    connect(alignCenterAct, &QAction::triggered, [=]()
            { editor->setAlignment(Qt::AlignCenter); });

    QAction *alignRightAct = toolBar->addAction(QIcon(":/editIcon/resoures/editIcon/alignRightAct.png"), "右对齐");
    alignRightAct->setCheckable(true);
    connect(alignRightAct, &QAction::triggered, [=]()
            { editor->setAlignment(Qt::AlignRight); });

    toolBar->addSeparator();

    // 插入图片
    QAction *insertImageAct = toolBar->addAction("插入图片");
    connect(insertImageAct, &QAction::triggered, [=]()
            {
    QString imagePath = QFileDialog::getOpenFileName(this, "选择图片", "", "Images (*.png *.jpg *.bmp)");
    if (!imagePath.isEmpty()) {
        QImage image;
        if (!image.load(imagePath)) {
            QMessageBox::warning(this, "插入图片失败", "无法加载图片文件，请选择有效的图片！");
            return;
        }

        // 等比缩放：宽度不超过ImageMaxWidth
        if (image.width() > ImageMaxWidth) {
            image = image.scaledToWidth(ImageMaxWidth, Qt::SmoothTransformation);
        }

        // 高度是否超过10000像素
        if (image.height() > 10000) {
            QMessageBox::warning(this, "插入图片失败", "图片过大，无法插入");
            return;
        }

        // 转换为JPG
        QByteArray byteArray;
        QBuffer buffer(&byteArray);
        buffer.open(QIODevice::WriteOnly);
        image.save(&buffer, "JPG");

        QString base64 = QString("data:image/jpeg;base64,%1").arg(QString(byteArray.toBase64()));
        editor->insertHtml("<br>"); // 换行
        editor->insertHtml(QString("<img src='%1' />").arg(base64));
    } });

    toolBar->setStyleSheet(R"(
        QToolButton {
            border-radius: 4px;
            background-color: #f0f0f0;
        }
        QToolButton:hover {
            background-color: #dcdcdc;
        }
    )");
}

QString CreatePage::getTitle() const
{
    return titleEdit->text();
}

QString CreatePage::getHtmlContent() const
{
    return editor->toHtml();
}

QString CreatePage::getSummary() const
{
    QString plainText = editor->toPlainText().simplified();
    if (plainText.length() <= 200)
    {
        return plainText;
    }
    else
    {
        return plainText.left(200) + "…";
    }
}

void CreatePage::setTitle(const QString &title)
{
    titleEdit->setText(title);
}
void CreatePage::setHtmlContent(const QString &htmlContent)
{
    editor->setHtml(htmlContent);
}